package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;

@Slf4j
public class AliOssUtil {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    public AliOssUtil(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.bucketName = bucketName;
    }

    public String upload(byte[] bytes, String objectName) {
        log.info("开始上传文件到OSS，endpoint: {}, bucketName: {}", endpoint, bucketName);

        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));

            // 修复URL格式：移除endpoint中的https://
            String cleanEndpoint = endpoint.replace("https://", "").replace("http://", "");
            String url = "https://" + bucketName + "." + cleanEndpoint + "/" + objectName;
            log.info("文件上传成功: {}", url);
            return url;

        } catch (OSSException oe) {
            log.error("OSS异常: ErrorCode={}, ErrorMessage={}", oe.getErrorCode(), oe.getErrorMessage());
            throw new RuntimeException("OSS上传失败: " + oe.getErrorMessage());
        } catch (ClientException ce) {
            log.error("网络异常: {}", ce.getMessage());
            throw new RuntimeException("网络连接失败: " + ce.getMessage());
        } catch (Exception e) {
            log.error("上传异常: ", e);
            throw new RuntimeException("上传失败: " + e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}